//
//  RBGroupDetailVC.m
//  zhongzhenglu
//
//  Created by XL on 2022/7/27.
//

#import "RBGroupDetailVC.h"
#import "RBDefine.h"
#import "UIView+RBAdd.h"
#import "UIScrollView+RBAdd.h"
#import <Masonry.h>
#import "RBThemeConfig.h"
#import <UIColor+YYAdd.h>
#import <UIView+YYAdd.h>
#import "RBPager.h"
#import "RanTool.h"
#import "UIViewController+RBAdd.h"
#import "RBHomeBannerView.h"
#import "RBGroupDetailGroupItemView.h"
#import "RBGradientView.h"
#import "RBGroupDetailGroupItemView.h"
#import "RBGroupAloneBuyVC.h"
#import "RBGroupDetailResponse.h"
#import "RBTimer.h"
#import "RBWebViewController.h"
#import "UIImageView+RBAdd.h"
#import "RBGroupDoneVC.h"
#import "RBGoodsDetailWebView.h"
#import "RBShopDetailVC.h" //店铺

@interface RBGroupDetailVC ()

@property(nonatomic, strong)UIScrollView *scrollView;
@property(nonatomic, strong)RBHomeBannerView *bannerView;

@property(nonatomic, strong)IBOutlet UIView *infoView;
@property(nonatomic, strong)IBOutlet UILabel *priceL;
@property(nonatomic, strong)IBOutlet UILabel *orgPriceL;
@property(nonatomic, strong)IBOutlet UILabel *timeL;
@property(nonatomic, strong)IBOutlet UILabel *groupL;
@property(nonatomic, strong)IBOutlet UILabel *nameL;
@property(nonatomic, strong)IBOutlet UILabel *desL;
@property(nonatomic, strong)IBOutlet UIView *shareView;

@property(nonatomic, strong)UIView *groupView;
@property(nonatomic, strong)IBOutlet UIView *groupTitleView;
@property(nonatomic, strong)IBOutlet UIView *groupRuleView;

@property(nonatomic, strong)UIView *detailView;
@property(nonatomic, strong)IBOutlet UIView *shopView;
@property(nonatomic, strong)IBOutlet UIImageView *shopImgView;
@property(nonatomic, strong)IBOutlet UILabel *shopNameL;
@property(nonatomic, strong)IBOutlet UILabel *shopDesL;

@property(nonatomic, strong)IBOutlet UIView *bottomView;
@property(nonatomic, strong)IBOutlet UIView *shopActionView;
@property(nonatomic, strong)IBOutlet UIView *serviceActionView;
@property(nonatomic, strong)IBOutlet UIView *collectActionView;
@property(nonatomic, strong)IBOutlet UIImageView *collectImgView;
@property(nonatomic, strong)IBOutlet UILabel *collectLabel;
@property(nonatomic, strong)IBOutlet UIView *aloneBuyView;
@property(nonatomic, strong) UIView *aloneBuyBgView;
@property(nonatomic, strong)IBOutlet UIView *groupBuyView;
@property(nonatomic, strong) UIView *groupBuyBgView;

@property(nonatomic, strong) RBGroupDetailResponse *response;
@property(nonatomic, strong) RBTimer *timer;

/**
    尝试通过刷新数据来校正页面
    后台数据不正确的情况下会校正失败,为了防止无休止刷新,只做一次校正
 */
@property(nonatomic, assign) BOOL triedToAjustByReloadData;

@end

@implementation RBGroupDetailVC

#pragma mark - Lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setup];
    __weak typeof(self) weak_self = self;
    [self.timer startTimerWithInterval:1 block:^(float countF, NSInteger countI) {
        [weak_self reloadTimeDisplay];
    }];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self getData];
}

#pragma mark - Private

- (void)setup
{
    self.title = @"拼团详情";
    [self.bottomView zoomSubViewsWithSelf];
    {
        RBGradientView *view = [RBGradientView gradientViewWithColors:@[[UIColor colorWithHexString:@"#F87628"],[UIColor colorWithHexString:@"#F23030"]] locations:nil vertical:NO];
        self.aloneBuyBgView = view;
        [self.aloneBuyView insertSubview:view atIndex:0];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
    }
    {
        RBGradientView *view = [RBGradientView gradientViewWithColors:@[[UIColor colorWithHexString:@"#518CFF"],[UIColor colorWithHexString:@"#2A6DF0"]] locations:nil vertical:NO];
        self.groupBuyBgView = view;
        [self.groupBuyView insertSubview:view atIndex:0];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
    }
    [self.aloneBuyView rbAddTapGesWithTarget:self action:@selector(aloneBuyBtnTapped)];
    [self.groupBuyView rbAddTapGesWithTarget:self action:@selector(groupBuyBtnTapped)];
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-kRBSafeBottomHeight);
        make.height.mas_equalTo(Zoom(self.bottomView.height));
    }];
    self.bottomView.hidden = YES;
    
    [self.infoView zoomSubViewsWithSelf];
    [self.groupTitleView zoomSubViewsWithSelf];
    self.groupTitleView.height = Zoom(self.groupTitleView.height);
    [self.groupRuleView zoomSubViewsWithSelf];
    [self.shopView zoomSubViewsWithSelf];
    
    //店铺
    [self.shopActionView rbAddTapGesWithTarget:self action:@selector(clickShopAction)];
    //客服
    [self.serviceActionView rbAddTapGesWithTarget:self action:@selector(clickContactCustomeTapped)];
    //收藏
    [self.collectActionView rbAddTapGesWithTarget:self action:@selector(clickCollectionTapped)];
}

- (void)fillData
{
    [self reloadCollect];
    __weak typeof(self) weak_self = self;
    self.bottomView.hidden = NO;
    if(self.response.data.btn_status == 1)
    {//进行中
        self.aloneBuyBgView.hidden = NO;
        self.groupBuyBgView.hidden = NO;
    }
    else
    {//未开始/已结束
        self.aloneBuyBgView.hidden = YES;
        self.groupBuyBgView.hidden = YES;
    }
    
    [self.scrollView rbSetContentWidth:kRBMainScreenWidth];
    self.bannerView.dataSource = self.response.data.picarr;
    [self.scrollView addView:self.bannerView withHeight:self.bannerView.height width:self.bannerView.width top:0 bottom:0 left:0 right:0 centerX:0];
    self.priceL.attributedText = [RanTool attributeStringMaker:^(NSMutableArray *maker) {
        [maker addAttributeStringWithFont:[UIFont boldSystemFontOfSize:Zoom(17)] color:UIColor.whiteColor string:@"¥"];
        [maker addAttributeStringWithFont:[UIFont boldSystemFontOfSize:Zoom(30)] color:UIColor.whiteColor string:[RanTool priceFromPrice:self.response.data.group_price][0]];
        [maker addAttributeStringWithFont:[UIFont boldSystemFontOfSize:Zoom(24)] color:UIColor.whiteColor string:@"."];
        [maker addAttributeStringWithFont:[UIFont boldSystemFontOfSize:Zoom(24)] color:UIColor.whiteColor string:[RanTool priceFromPrice:self.response.data.group_price][1]];
    }];
    self.orgPriceL.attributedText = [RanTool attributeStringMaker:^(NSMutableArray *maker) {
        [maker addAttributeStringWithFont:[UIFont systemFontOfSize:Zoom(13)] color:[UIColor colorWithHexString:@"#FFC9C9"] string:[NSString stringWithFormat:@"原价：¥%@", self.response.data.goods_price] lineSpacing:0 througnLineHeight:1 throughLineColor:[UIColor colorWithHexString:@"#FFC9C9"]];
    }];
    [self reloadTimeDisplay];
    self.groupL.text = [NSString stringWithFormat:@"%@人团", self.response.data.group_people_max];
    self.nameL.text = self.response.data.goods_title;
    self.desL.text = self.response.data.remark;
    
    [self.scrollView addView:self.infoView withHeight:CGFLOAT_MIN width:Zoom(350) top:Zoom(15) bottom:0 left:CGFLOAT_MIN right:CGFLOAT_MIN centerX:YES];
    [self.scrollView addView:({
        UIView *view = UIView.new;
        [view rbSetCornerRadius:Zoom(8)];
        view.backgroundColor = UIColor.whiteColor;
        
        if(self.response.data.group_activity.count && self.response.data.btn_status == 1)
        {
            [view view_addView:self.groupTitleView withHeight:Zoom(51) width:CGFLOAT_MIN top:0 bottom:0 left:0 right:0 centerX:0];
            for (RBGroupDetailAtyModel *model in self.response.data.group_activity)
            {
                RBGroupDetailGroupItemView *itemView = [RBGroupDetailGroupItemView view];
                itemView.model = model;
                itemView.joinBlock = ^(RBGroupDetailAtyModel * _Nonnull model) {
                    RBGroupDoneVC *vc = RBGroupDoneVC.new;
                    vc.type = 1;
                    vc.group_activity_id = model.group_activity_id;
                    [weak_self.navigationController pushViewController:vc animated:YES];
                };
                [view view_addView:itemView withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(0) bottom:Zoom(0) left:Zoom(15) right:Zoom(15) centerX:0];
            }
        }
        
        [view view_addView:self.groupRuleView withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(17) bottom:Zoom(17) left:Zoom(15) right:Zoom(15) centerX:0];
        
        view;
    }) withHeight:CGFLOAT_MIN width:Zoom(350) top:Zoom(10) bottom:0 left:CGFLOAT_MIN right:CGFLOAT_MIN centerX:YES];
    [self.scrollView addView:({
        UIView *view = UIView.new;
        [view rbSetCornerRadius:Zoom(8)];
        view.backgroundColor = UIColor.whiteColor;
        
        [self.shopImgView setImageWithUrl:self.response.data.store_logo placeHolder:nil];
        self.shopNameL.text = self.response.data.store_name;
        self.shopDesL.text = self.response.data.store_desc;
        [view view_addView:self.shopView withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(19) bottom:Zoom(15) left:0 right:0 centerX:0];
        
        RBGoodsDetailWebView *webView = RBGoodsDetailWebView.new;
        webView.autoUpdateHeight = YES;
        [view view_addView:webView withHeight:10 width:CGFLOAT_MIN top:Zoom(10) bottom:Zoom(15) left:Zoom(12) right:Zoom(12) centerX:0];
        webView.content = self.response.data.goods_con;
        
        view;
    }) withHeight:CGFLOAT_MIN width:Zoom(350) top:Zoom(10) bottom:Zoom(10) left:CGFLOAT_MIN right:CGFLOAT_MIN centerX:YES];
}

#pragma mark - 活动时间刷新

- (void)reloadTimeDisplay
{
    if(!self.response)
    {
        return;
    }
    //针对未开始和进行中的倒计时校验一次
    if(!self.triedToAjustByReloadData)
    {
        if(self.response.data.btn_status == 2)
        {
            if([NSDate.date timeIntervalSince1970] - self.response.data.start_time <= 0)
            {//活动开始
                self.triedToAjustByReloadData = YES;
                [self getData];
                return;
            }
        }
        else if(self.response.data.btn_status == 1)
        {
            if(self.response.data.end_time - [NSDate.date timeIntervalSince1970] <= 0)
            {//活动结束
                self.triedToAjustByReloadData = YES;
                [self getData];
                return;
            }
        }
    }
    
    CGFloat padding = Zoom(5);
    UIColor *color = UIColor.whiteColor;
    UIFont *bigFont = [UIFont systemFontOfSize:Zoom(14) weight:UIFontWeightMedium];
    UIFont *smallFont = [RanTool numFontWithSize:Zoom(12)];
    if(self.response.data.btn_status == 3)
    {
        self.timeL.attributedText = [RanTool attributeStringMaker:^(NSMutableArray *maker) {
            [maker addAttributeStringWithFont:bigFont color:color string:@"活动已结束" lineSpacing:padding];
        }];
    }
    else if(self.response.data.btn_status == 1)
    {
        self.timeL.attributedText = [RanTool attributeStringMaker:^(NSMutableArray *maker) {
            [maker addAttributeStringWithFont:bigFont color:color string:@"距离活动结束" lineSpacing:padding];
            [maker addAttributeStringWithFont:smallFont color:color string:@"\n" lineSpacing:padding];
            [maker addAttributeStringWithFont:smallFont color:color string:[self countDownTimeFromTimeStamp:self.response.data.end_time - [NSDate.date timeIntervalSince1970]] lineSpacing:padding];
        }];
    }
    else if(self.response.data.btn_status == 2)
    {
        self.timeL.attributedText = [RanTool attributeStringMaker:^(NSMutableArray *maker) {
            [maker addAttributeStringWithFont:bigFont color:color string:@"距离活动开始" lineSpacing:padding];
            [maker addAttributeStringWithFont:smallFont color:color string:@"\n" lineSpacing:padding];
            [maker addAttributeStringWithFont:smallFont color:color string:[self countDownTimeFromTimeStamp:[NSDate.date timeIntervalSince1970] - self.response.data.start_time] lineSpacing:padding];
        }];
    }
    self.timeL.numberOfLines = 0;
    self.timeL.textAlignment = NSTextAlignmentRight;
}

- (NSString *)countDownTimeFromTimeStamp: (double)timeStamp
{
    NSArray *timeArray = [RanTool dayHourMinuteSecondFromInterval:timeStamp];
    NSMutableString *stringM = NSMutableString.string;
    NSString *dayStr = timeArray[0];
    if(dayStr.intValue)
    {
        [stringM appendFormat:@"%@天",timeArray[0]];
    }
    [stringM appendFormat:@"%@：%@：%@",timeArray[1],timeArray[2],timeArray[3]];
    return stringM;
}

#pragma mark - Network

- (void)getData
{
    __weak typeof(self) weak_self = self;
    [self viewLoadDataWithParam:^(NSMutableDictionary *dicM) {
        dicM[@"group_id"] = self.id;
    } path:@"hu_group_show" post:YES log:YES responseClass:RBGroupDetailResponse.class desView:self.view showHud:YES showPlaceHolder:NO sucBlock:^(id data) {
        weak_self.response = data;
        [weak_self fillData];
    } failBlock:^(RBGroupDetailResponse *data) {
        [weak_self.view showTip:data.message completion:nil];
    } reloadBlock:nil];
}

#pragma mark - Event
- (IBAction)clickShopBtn:(UIButton *)sender {
    [self clickShopAction];
}
//店铺
- (void)clickShopAction {
    RBShopDetailVC *vc = RBShopDetailVC.new;
    vc.id = self.response.data.store_id;
    [self.navigationController pushViewController:vc animated:YES];
}
//客服
- (void)clickContactCustomeTapped {
    [UIApplication LC_openURL_phone:self.response.data.mobile];
}
//收藏
- (void)clickCollectionTapped {
    LCWeakSelf;
    [self.defaultHm requestWithParam:^(NSMutableDictionary *dicM) {
        dicM[@"goodsid"] = self.id;
        dicM[@"type"] = @"2";
    } log:YES post:YES cancelLastRequest:NO fileParam:nil fileProgress:nil responseClass:RBResponse.class pathName:@"han_store_do_collect" completion:^(RBResponse *response) {
        if (response.succeed) {
            if ([self.response.data.is_collect isEqualToString:@"Y"]) {
                self.response.data.is_collect = @"N";
            } else {
                self.response.data.is_collect = @"Y";
            }
            
            [weakSelf reloadCollect];
            
            [JKToast showWithText:response.message];
        }
    }];
}
//刷新收藏
- (void)reloadCollect {
    if ([self.response.data.is_collect isEqualToString:@"Y"]) {
        self.collectImgView.image = [UIImage imageNamed:@"orderDetailCollect"];
        self.collectLabel.text = @"已收藏";
    } else {
        self.collectImgView.image = [UIImage imageNamed:@"orderDetailCollect"];
        self.collectLabel.text = @"收藏";
    }
}

- (IBAction)ruleBtnTapped
{
    RBWebViewController *vc = RBWebViewController.new;
    vc.naviTitle = @"拼团规则";
    vc.html = self.response.data.guize;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)aloneBuyBtnTapped
{
    if(self.response.data.btn_status == 2)
    {
        [self.view showTip:@"活动未开始" completion:nil];
        return;
    }
    else if(self.response.data.btn_status == 3)
    {
        [self.view showTip:@"活动已结束" completion:nil];
        return;
    }
    
    __weak typeof(self) weakSelf = self;
    UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"提示" message:@"确认购买，不选择更优惠的团购？" preferredStyle:UIAlertControllerStyleAlert];
    [vc addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [vc addAction:[UIAlertAction actionWithTitle:@"确认购买" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        RBGroupAloneBuyVC *vc = RBGroupAloneBuyVC.new;
        vc.group_id = weakSelf.id;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }]];
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)groupBuyBtnTapped
{
    if(self.response.data.btn_status == 2)
    {
        [self.view showTip:@"活动未开始" completion:nil];
        return;
    }
    else if(self.response.data.btn_status == 3)
    {
        [self.view showTip:@"活动已结束" completion:nil];
        return;
    }
    
    RBGroupAloneBuyVC *vc = RBGroupAloneBuyVC.new;
    vc.type = 1;
    vc.group_id = self.id;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Setter

#pragma mark - Getter

- (UIScrollView *)scrollView
{
    if (!_scrollView)
    {
        self.scrollView = ({
            UIScrollView *view = UIScrollView.new;
            view.backgroundColor = [RBThemeConfig bgGrayColor];
            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.top.mas_equalTo(0);
                make.bottom.mas_equalTo(self.bottomView.mas_top);
            }];
            view;
        });
    }
    return _scrollView;
}

- (RBHomeBannerView *)bannerView
{
    if (!_bannerView)
    {
        self.bannerView = ({
            RBHomeBannerView *view = RBHomeBannerView.new;
            [view rbSetCornerRadius:0];
            view.width = kRBMainScreenWidth;
            view.height = Zoom(265);
            view;
        });
    }
    return _bannerView;
}

- (RBTimer *)timer
{
    if(!_timer)
    {
        self.timer = RBTimer.new;
    }
    return _timer;
}

@end
